package com.itic.mall.mobile.users.invite;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.DefaultSysSettingKeyValue;
import com.itic.appbase.framework.type.UserType;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.mobile.share.LinkVo;
import com.itic.mall.system.finance.makeMoneyLog.service.FinanceUserMakeMoneyLogService;
import com.itic.mall.system.users.giveMoney.persistence.model.UsersGiveMoney;
import com.itic.mall.system.users.giveMoney.service.UsersGiveMoneyService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMallExample.Criteria;

/**
 * 邀请入驻接口
 * @author 许小宝
 * @time 2017-12-4
 */

@Controller
@RequestMapping(value="/mobile/users/invite")
public class InviteInterface extends BaseMobileInterface{
	@Autowired
	private UsersGiveMoneyService UsersGiveMoneyService;
	/**
	 * 云店主邀请VIP用户注册
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/regVip")
	@ResponseBody
	public Map<String,Object> regVip( HttpServletRequest request,HttpServletResponse response, String phone, String code, String parentId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	String defaultValue = DefaultSysSettingKeyValue.downAppLink.getValue();
	    	String sysWord = sysSettingService.getByKey(DefaultSysSettingKeyValue.downAppLink.getValue());
			if( StringHelper.isNotBlank(sysWord) ){
				defaultValue = sysWord;
			}
			resultMap.put(DATA, defaultValue);
			
	    	if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) && StringHelper.isNotBlank(parentId) ){
	    		UsersMall parentUser = usersMallService.get(parentId);
	    		//邀请人是否有效
	    		if( null != parentUser ){
	    			//判断手机号码是否注册过
		   			UsersMall usersTemp = usersMallService.getByPhone(phone);
		   			if( null == usersTemp ){
		   				//验证码是否有效code
		   				if( isEffectiveCode(phone,code) ){
		   					//注册手机号码
		   					UsersMall user = new UsersMall();
		   					user.setUserPhone(phone);
		   					user.setLaiyuan("公众号");
		   					if( UserType.ydz.getType().equals(parentUser.getType())){
		   						//user.setParentId(parentId);
		   						user.setYunId(parentId);
		   					}
		   					
		   					user.setInvitedId(parentId);
		   					usersMallService.reg(user);
		   					//VIP注册赠送200生息本金
		   					this.UsersGiveMoneyService.userRegistMoney(user, 200, 200);
					   		errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{
					   		errorCode = PHONE_CODE_ERROR_CODE;
					       	errorMsg = PHONE_CODE_ERROR_MSG;
		   				}
		   			}else{
		   		     	//提示用户号码已注册过了
		   				errorCode = PHONE_REGED_ERROR_CODE;
				       	errorMsg = PHONE_REGED_ERROR_MSG;
		   			}
	    		}else{
	   				errorCode = PARENT_ID_ERROR_CODE;
			       	errorMsg = PARENT_ID_ERROR_MSG;
	    		}
	    	}
	    	
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "regVip", e.toString(),"APP进入我的页面接口信息",e);
	    }
	    
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	/**
	 * 云店主邀请VIP用户注册
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/regYun")
	@ResponseBody
	public Map<String,Object> regYun( HttpServletRequest request,HttpServletResponse response, String phone, String code, String parentId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	String defaultValue = DefaultSysSettingKeyValue.downAppLink.getValue();
	    	String sysWord = sysSettingService.getByKey(DefaultSysSettingKeyValue.downAppLink.getValue());
			if( StringHelper.isNotBlank(sysWord) ){
				defaultValue = sysWord;
			}
			resultMap.put(DATA, defaultValue);
	    	if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) && StringHelper.isNotBlank(parentId) ){
	    		UsersMall parentUser = usersMallService.get(parentId);
	    		if( null != parentUser ){
	    			UsersMall usersTemp = usersMallService.getByPhone(phone);
		   			if( null == usersTemp ){
		   				if( isEffectiveCode(phone,code) ){
		   				    //注册手机号码
		   					UsersMall user = new UsersMall();
		   					user.setUserPhone(phone);
		   					user.setParentId(parentId);
		   					user.setYunId(parentId);
		   					user.setInvitedId(parentId);
		   					user.setInvitingCode(getYunInviteCode());
		   					user.setType(UserType.ydz.getType());
		   					user.setLaiyuan("公众号");
		   					user.setJifeng(10);
		   					usersMallService.reg(user);
		   					errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{
					   		errorCode = PHONE_CODE_ERROR_CODE;
					       	errorMsg = PHONE_CODE_ERROR_MSG;
		   				}
		   			}else{
		   		     	//提示用户号码已注册过了
		   				errorCode = PHONE_REGED_ERROR_CODE;
				       	errorMsg = PHONE_REGED_ERROR_MSG;
		   			}
	    		}else{
	    			errorCode = PARENT_ID_ERROR_CODE;
			       	errorMsg = PARENT_ID_ERROR_MSG;
	    		}
	    	}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "regYun", e.toString(),"APP进入我的页面接口信息",e);
	    }
	   
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	/**
	 * 云店主邀请VIP用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/getInviteCodeByParentId")
	@ResponseBody
	public Map<String,Object> getInviteCodeByParentId( HttpServletRequest request,HttpServletResponse response, String parentId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	   		if( StringHelper.isNotBlank(parentId) ){
	   			UsersMall usersMall = usersMallService.get(parentId);
	   			if( null != usersMall && UserType.ydz.getType().equals(usersMall.getType()) ){
	   				resultMap.put(DATA, usersMall.getInvitingCode());
	   				errorCode = SUCCESS_ERROR_CODE;
			       	errorMsg = SUCCESS_ERROR_MSG;
	   			}else{
	   				errorCode = PARENT_ID_ERROR_CODE;
	   		       	errorMsg = PARENT_ID_ERROR_MSG;
	   			}
	   		}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "getInviteCodeByParentId", e.toString(),"根据用户parentId获取用户邀请码",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
    
	/**
	 * 云店主邀请VIP用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/vip")
	@ResponseBody
	public Map<String,Object> vip( HttpServletRequest request,HttpServletResponse response, String token, String appId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	   		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
	   			UsersMall user = getUsersByTokenAndAppId(token, appId);
	   			if( null != user ){
	   				
	   				Map<String, Object> dataMap = new HashMap<String,Object>();
	   				dataMap.put("name", user.getUserNickName()==null?"未设置名称":user.getUserNickName());//用户名称
	   				dataMap.put("headimg", getDefaultHeadImg());//用户头像
	   				if( StringHelper.isNotBlank(user.getUserHeadImg()) ){
	   					dataMap.put("headimg", user.getUserHeadImg());
	   				}
	   				//用户的二维码
	   				if( StringHelper.isNotBlank(user.getInvitingQcode()) ){
	   					dataMap.put("qrcode", user.getInvitingQcode());//用户邀请二维码
	   				}else{
	   					String qcodeByUsers = getInvitingQcodeByUsers(user);
	   					dataMap.put("qrcode", qcodeByUsers);//用户邀请二维码
	   					user.setInvitingQcode(qcodeByUsers);
	   				}
	   				//邀请二维码海报
	   				if( StringHelper.isNotBlank(user.getInvitingImg())){
	   					dataMap.put("invitingImg", user.getInvitingImg());//用户邀请码
	   				}else{
	   					String imgByUsers = getInvitingImgByUsers(user);
	   					dataMap.put("invitingImg", imgByUsers);//用户邀请码
	   					user.setInvitingImg(imgByUsers);
	   				}
	   				
	   				dataMap.put("tipword", getVipTipword());
	   				
	   			    //链接分享
					LinkVo urlVo = new LinkVo();
					urlVo.setImgUrl("http://file.jhjvip.cn/yhjlogo.png");
					urlVo.setTitle(user.getUserNickName()+"邀请注册友惠家VIP");
					urlVo.setContent(user.getUserNickName()+"赠送了您10元现金新手礼劵，邀请您成为友惠家VIP" );
					
					String inviteVipUrl = DefaultSysSettingKeyValue.inviteVipLink.getValue()+user.getId();
					String tempInvite = sysSettingService.getByKey(DefaultSysSettingKeyValue.inviteVipLink.getKey());
					if( StringHelper.isNotBlank(tempInvite) ){
						inviteVipUrl = tempInvite+user.getId();
					}
					urlVo.setUrl(inviteVipUrl);
					dataMap.put("link", urlVo);//链接
	   				
	   				usersMallService.edit(user);
	   				resultMap.put(DATA,dataMap);
	   				
	   				errorCode = SUCCESS_ERROR_CODE;
	   		       	errorMsg = SUCCESS_ERROR_MSG;
	   		       	
	   			}else{
	   				errorCode = LOGIN_ERROR_CODE;
	   		       	errorMsg = LOGIN_ERROR_MSG;
	   			}
	   		}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"云店主邀请VIP用户",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	
	/**
	 * 邀请云店主
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/yun")
	@ResponseBody
	public Map<String,Object> yun( HttpServletRequest request,HttpServletResponse response, String token, String appId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	   		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
	   			UsersMall user = getUsersByTokenAndAppId(token, appId);
	   			//判断是否为云店主
	   			if( null != user && "002".equals(user.getType()) ){
	   				Map<String, Object> dataMap = new HashMap<String,Object>();
	   				dataMap.put("name", user.getUserNickName()==null?"未设置名称":user.getUserNickName());//用户名称
	   				/*dataMap.put("headimg", getDefaultHeadImg());//用户头像
	   				if( StringHelper.isNotBlank(user.getUserHeadImg()) ){
	   					dataMap.put("headimg", user.getUserHeadImg());
	   				}*/
	   				dataMap.put("invitingCode", user.getInvitingCode()==null?"000000":user.getInvitingCode());//用户邀请码
	   				//用户的二维码
	   				if( StringHelper.isNotBlank(user.getInvitingQcodeYun()) ){
	   					dataMap.put("qrcode", user.getInvitingQcodeYun());//用户邀请二维码
	   				}else{
	   					String qcodeByUsers = getInvitingQcodeYunByUsers(user);
	   					dataMap.put("qrcode", qcodeByUsers);//用户邀请二维码
	   					user.setInvitingQcodeYun(qcodeByUsers);
	   				}
	   				if( StringHelper.isNotBlank(user.getInvitingImgYun())){
	   					dataMap.put("invitingImg", user.getInvitingImgYun());//用户邀请码
	   				}else{//需要动态生成一个图片
	   					String invitingImgYunByUsers = getInvitingImgYunByUsers(user);
	   					dataMap.put("invitingImg", invitingImgYunByUsers);//用户邀请码
	   					user.setInvitingImgYun(invitingImgYunByUsers);
	   				}
	   				
	   				//dataMap.put("showImgs", getShowImgs());
	   				dataMap.put("tipword", getYunTipword());
	   				usersMallService.edit(user);
	   				
	   			    //链接分享
					LinkVo urlVo = new LinkVo();
					urlVo.setImgUrl("http://file.jhjvip.cn/yhjlogo.png");
					urlVo.setTitle(user.getUserNickName()+"邀请你开启手机开店之旅 ");
					urlVo.setContent("轻松三步骤即可开通你的小程序微店~" );
					String defaultValue = DefaultSysSettingKeyValue.inviteYunLink.getValue();
					String sysWord = sysSettingService.getByKey(DefaultSysSettingKeyValue.inviteYunLink.getKey());
					if( StringHelper.isNotBlank(sysWord) ){
						defaultValue = sysWord;
					}
					urlVo.setUrl(defaultValue+user.getId());
					
					dataMap.put("link", urlVo);//链接
					
	   				resultMap.put(DATA,dataMap);
	   				
	   				errorCode = SUCCESS_ERROR_CODE;
	   		       	errorMsg = SUCCESS_ERROR_MSG;
	   			}else{
	   				errorCode = Not_OPEND_YDZ_ERROR_CODE;
	   		       	errorMsg = Not_OPEND_YDZ_ERROR_MSG;
	   			}
	   		}
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"APP进入我的页面接口信息",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}
	
	
	/**
	 * vip列表
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/listVip")
	@ResponseBody
	public Map<String,Object> listVip( HttpServletRequest request,HttpServletResponse response, String token, String appId ){
		String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	    try{
	    	if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
	    		UsersMall user = getUsersByTokenAndAppId(token, appId);
	    		if( null != user ){
	    			Map<String, Object> dataMap = new HashMap<String, Object>();
	 			   
	    	    	UsersMallExample example = new UsersMallExample();
	    	    	example.setOrderByClause("CREATE_TIME DESC");
	    			Criteria criteria = example.createCriteria();
	    			
	    			criteria.andIsEffectiveEqualTo(DBConst.TRUE);// 是否有效
	    			criteria.andInvitedIdEqualTo(user.getId());

	    			this.handlePageQueryDefault(request, example);// 分页
	    			int count = usersMallService.count(example);// 总条数
	    			List<UsersMall> list = usersMallService.list(example);// 数据list

	    			dataMap.put("total", count);
	    			dataMap.put("isMore", isMore(request, count));
	    			
	    			dataMap.put("image", getListImage());
	    			
	    			dataMap.put("first", ValueHelper.transBean2Map(user,null,
	    					new String[] { "isEffective", "updateTime", "orgCode", "createUser", "reorder",
	    							"note", "unionid", "invitingCode", "money",
	    							"parentId", "preProfit", "successPeopleOne", "jifeng", "laiyuan", "openid", "totalProfit",
	    							"yunId", "isBlack", "userPwd", "vipLevel", "yunLevel", "isActive",
	    							"successPeopleTwo", "sex", "city", "birth", "totalComsum", "userNum", "aliId",
	    							"yunDealedOrder", "userRealName", "levelDesc", "invitingImg", "invitingQcode",
	    							"email" }));

	    			dataMap.put("list", ValueHelper.tranList2MapList(list,
	    					new String[] { "isEffective", "updateTime", "orgCode", "createUser", "reorder",
	    							"note", "unionid", "invitingCode", "money",
	    							"parentId", "preProfit", "successPeopleOne", "jifeng", "laiyuan", "openid", "totalProfit",
	    							"yunId", "isBlack", "userPwd", "vipLevel", "yunLevel", "isActive",
	    							"successPeopleTwo", "sex", "city", "birth", "totalComsum", "userNum", "aliId",
	    							"yunDealedOrder", "userRealName", "levelDesc", "invitingImg", "invitingQcode",
	    							"email" }));

	    			resultMap.put(DATA, dataMap);
	    			errorCode = SUCCESS_ERROR_CODE;
	    	       	errorMsg = SUCCESS_ERROR_MSG;
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
		    	}
	    	}
	    	
	    }catch(Exception e){
	    	errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	   		logException("UserdataInterface", "index", e.toString(),"APP进入我的页面接口信息",e);
	    }
	    resultMap.put(CODE, errorCode);
	    resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
	    return resultMap;
	}



	/**
	 * 获取轮播图广告
	 * @return
	 */
	private Object getListImage() {
		String result = DefaultSysSettingKeyValue.listImageInviteNewVip.getValue();
		String byKey = sysSettingService.getByKey(DefaultSysSettingKeyValue.listImageInviteNewVip.getKey());
		if( StringHelper.isNotBlank(byKey) ){
			result = byKey;
		}
		return result;
	}


	private String getYunTipword() {
		String result = DefaultSysSettingKeyValue.inviteTipYunWord.getValue();
		String sysWord = sysSettingService.getByKey(DefaultSysSettingKeyValue.inviteTipYunWord.getKey());
		if( StringHelper.isNotBlank(sysWord) ){
			result = sysWord;
		}
		return result;
	}
	
	/**
	 * 邀请VIP时配置信息
	 * @return
	 */
	private String getVipTipword() {
		String result = DefaultSysSettingKeyValue.inviteTipVipWord.getValue();
		String sysWord = sysSettingService.getByKey(DefaultSysSettingKeyValue.inviteTipVipWord.getValue());
		if( StringHelper.isNotBlank(sysWord) ){
			result = sysWord;
		}
		return result;
	}

	/*private List<String> getShowImgs() {
		List<String> result = new ArrayList<String>();
		result.add("http://file.jhjvip.cn/showimg1.jpg");
		result.add("http://file.jhjvip.cn/showimg2.jpg");
		return result;
	}*/

	/**
	 * 邀请普通用户生成的二维码
	 * @param user
	 * @return
	 */
	private String getInvitingQcodeByUsers(UsersMall user) {
		return usersMallService.getInvitingYunQcode(user);
		//return "http://file.jhjvip.cn/qrcode.jpg";
	}

	/**
	 * 邀请普通用户生成的海报
	 * @param user
	 * @return
	 */
	private String getInvitingImgByUsers(UsersMall user) {
		/*String defaultValue = DefaultSysSettingKeyValue.inviteTipVipWord.getValue();
		String sysWord = sysSettingService.getByKey(DefaultSysSettingKeyValue.inviteTipVipWord.getKey());
		if( StringHelper.isNotBlank(sysWord) ){
			defaultValue = sysWord;
		}*/
		//根据用户的信息生成二维码海报
	    return usersMallService.getInviteVipPoster(user, user.getUserNickName());
	    
	}
	
	/**
	 * 云店主邀请生成二维码
	 * @param user
	 * @return
	 */
	private String getInvitingQcodeYunByUsers(UsersMall user) {
		return usersMallService.getInvitingYunQcode(user);
		//return "http://file.jhjvip.cn/qrcode.jpg";
	}
	
	/**
	 * 云店主邀请生成二维码海报
	 */
	private String getInvitingImgYunByUsers(UsersMall user) {
		//根据用户的信息生成二维码海报
	   return usersMallService.getInviteYunPoster(user);
	    
	}
}
